<template>
  <div class="activity-management-container">
    <el-card class="filter-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>活动管理</h3>
          <el-button type="primary" @click="handleCreateActivity">
            <el-icon><plus /></el-icon> 新增活动
          </el-button>
        </div>
      </template>
      
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="活动标题">
          <el-input v-model="searchForm.title" placeholder="请输入活动标题" clearable />
        </el-form-item>
        
        <el-form-item label="活动状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="未发布" value="1" />
            <el-option label="已发布" value="2" />
            <el-option label="进行中" value="3" />
            <el-option label="已结束" value="4" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><search /></el-icon> 搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="table-card" shadow="hover">
      <el-table
        :data="activityList"
        border
        stripe
        highlight-current-row
        :row-key="row => row.id"
        @row-dblclick="handleEditActivity"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="title" label="活动标题" min-width="150" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusName(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="活动地点" min-width="120" />
        <el-table-column label="开始时间" min-width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column label="结束时间" min-width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="organizerId" label="组织者ID" width="100" align="center" />
        <el-table-column prop="maxParticipants" label="最大人数" width="100" align="center" />
        <el-table-column label="操作" width="260" align="center">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleEditActivity(row)"
              :disabled="row.status === 4"
            >
              <el-icon><edit /></el-icon> 编辑
            </el-button>
            <el-button 
              type="success" 
              size="small" 
              @click="publishActivity(row)"
              :disabled="row.status !== 1"
            >
              <el-icon><check /></el-icon> 发布
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDeleteActivity(row)"
              :disabled="row.status !== 1"
            >
              <el-icon><delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination" v-if="total > 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑活动对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑活动' : '新增活动'"
      width="40%"
    >
      <el-form 
        :model="formData" 
        :rules="rules" 
        ref="formRef" 
        label-width="100px"
      >
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入活动标题" />
        </el-form-item>
        
        <el-form-item label="活动内容" prop="content">
          <el-input 
            v-model="formData.content" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入活动内容"
          />
        </el-form-item>
        
        <el-form-item label="活动地点" prop="location">
          <el-input v-model="formData.location" placeholder="请输入活动地点" />
        </el-form-item>

        <el-date-picker
            v-model="formData.startTime"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm:ss" 
            value-format="YYYY-MM-DDTHH:mm:ss" 
            />

        <el-date-picker
            v-model="formData.endTime"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DDTHH:mm:ss"
        />
        
        <el-form-item label="组织者ID" prop="organizerId">
          <el-input v-model="formData.organizerId" placeholder="请输入组织者ID" />
        </el-form-item>
        
        <el-form-item label="最大人数" prop="maxParticipants">
          <el-input-number
            v-model="formData.maxParticipants"
            :min="1"
            :max="10000"
            placeholder="请输入最大参与人数"
          />
        </el-form-item>
        
        <el-form-item label="活动状态" prop="status" v-if="isEditMode">
          <el-select 
            v-model="formData.status" 
            placeholder="请选择状态"
            style="width: 100%"
          >
            <el-option label="未发布" value="1" />
            <el-option label="已发布" value="2" />
            <el-option label="进行中" value="3" />
            <el-option label="已结束" value="4" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveActivity">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="30%"
    >
      <p>确定要删除活动 <span class="user-name">{{ deleteActivityTitle }}</span> 吗？</p>
      <p class="warning-text">此操作仅允许删除未发布的活动！</p>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Plus,
  Search,
  Refresh,
  Edit,
  Delete,
  Check
} from '@element-plus/icons-vue';
import request from '@/utils/request';

// 搜索表单
const searchForm = reactive({
  title: '',
  status: ''
});

// 表格数据
const activityList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);

// 对话框状态
const dialogVisible = ref(false);
const isEditMode = ref(false);
const formData = reactive({
  id: null,
  title: '',
  content: '',
  location: '',
  startTime: '',
  endTime: '',
  organizerId: null,
  maxParticipants: 10,
  status: 1
});

// 表单验证规则
const rules = reactive({
  title: [
    { required: true, message: '请输入活动标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度在2-50个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入活动内容', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入活动地点', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    { validator: (rule, value, callback) => {
        if (value && formData.startTime && new Date(value) <= new Date(formData.startTime)) {
          callback(new Error('结束时间必须晚于开始时间'));
        } else {
          callback();
        }
      }, trigger: 'change' }
  ],
  organizerId: [
    { required: true, message: '请输入组织者ID', trigger: 'blur' },
    //{ type: 'number', message: '请输入有效的组织者ID', trigger: 'blur' }
  ],
  maxParticipants: [
    { required: true, message: '请输入最大参与人数', trigger: 'blur' },
    { type: 'number', min: 1, message: '最大参与人数至少为1', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择活动状态', trigger: 'change' }
  ]
});

// 删除对话框
const deleteDialogVisible = ref(false);
const deleteActivityId = ref(null);
const deleteActivityTitle = ref('');

// 表单引用
const formRef = ref(null);

// 生命周期钩子
onMounted(() => {
  fetchActivityList();
});

// 获取活动列表
const fetchActivityList = async () => {
  loading.value = true;
  
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      title: searchForm.title || undefined,
      status: searchForm.status || undefined
    };
    
    const response = await request.get('/activity-service/activity/list', { params });
    
    if (response.code === 200) {
      activityList.value = response.data.records || [];
      total.value = response.data.total || 0;
    } else {
      ElMessage.error(response.message || '获取活动列表失败');
    }
  } catch (error) {
    ElMessage.error('获取活动列表失败，请重试');
    console.error('获取活动列表错误:', error);
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchActivityList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.title = '';
  searchForm.status = '';
  currentPage.value = 1;
  fetchActivityList();
};

// 处理分页大小变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchActivityList();
};

// 处理当前页变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchActivityList();
};

// 打开新增活动对话框
const handleCreateActivity = () => {
  isEditMode.value = false;
  // 重置表单数据
  Object.assign(formData, {
    id: null,
    title: '',
    content: '',
    location: '',
    startTime: '',
    endTime: '',
    organizerId: null,
    maxParticipants: 10,
    status: 1
  });
  dialogVisible.value = true;
  
  // 重置表单验证
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate();
    }
  });
};

// 打开编辑活动对话框
const handleEditActivity = (row) => {
  isEditMode.value = true;
  // 复制数据到表单
  Object.assign(formData, {
    id: row.id,
    title: row.title,
    content: row.content,
    location: row.location,
    startTime: row.startTime,
    endTime: row.endTime,
    organizerId: row.organizerId,
    maxParticipants: row.maxParticipants,
    status: row.status
  });
  dialogVisible.value = true;
};

// 保存活动
const saveActivity = async () => {
  // 触发表单验证
  if (!formRef.value) return;
  
  const valid = await formRef.value.validate();
  if (!valid) return;
  
  try {
    let response;
    let successMessage;
    
    if (isEditMode.value) {
      // 编辑活动
      response = await request.post('/activity-service/activity/update', formData);
      successMessage = '活动更新成功';
    } else {
      // 新增活动
      response = await request.post('/activity-service/activity/add', formData);
      successMessage = '活动创建成功';
    }
    
    if (response.code === 200) {
      ElMessage.success(successMessage);
      dialogVisible.value = false;
      fetchActivityList();
    } else {
      ElMessage.error(response.message || (isEditMode.value ? '活动更新失败' : '活动创建失败'));
    }
  } catch (error) {
    ElMessage.error(isEditMode.value ? '活动更新失败，请重试' : '活动创建失败，请重试');
    console.error(isEditMode.value ? '更新活动错误' : '创建活动错误', error);
  }
};

// 发布活动
const publishActivity = async (row) => {
  try {
    const response = await request.post(`/activity-service/activity/publish/${row.id}`);
    
    if (response.code === 200) {
      ElMessage.success('活动发布成功');
      fetchActivityList();
    } else {
      ElMessage.error(response.message || '活动发布失败');
    }
  } catch (error) {
    ElMessage.error('活动发布失败，请重试');
    console.error('发布活动错误:', error);
  }
};

// 处理删除活动
const handleDeleteActivity = (row) => {
  if (row.status !== 1) {
    ElMessage.warning('只能删除未发布的活动');
    return;
  }
  
  deleteActivityId.value = row.id;
  deleteActivityTitle.value = row.title;
  deleteDialogVisible.value = true;
};

// 确认删除活动
const confirmDelete = async () => {
  try {
    const response = await request.post(`/activity-service/activity/delete?id=${deleteActivityId.value}`);
    
    if (response.code === 200) {
      ElMessage.success('活动删除成功');
      deleteDialogVisible.value = false;
      // 如果删除的是当前页最后一条数据，且不是第一页，则返回上一页
      if (activityList.value.length === 1 && currentPage.value > 1) {
        currentPage.value -= 1;
      }
      fetchActivityList();
    } else {
      ElMessage.error(response.message || '活动删除失败');
    }
  } catch (error) {
    ElMessage.error('活动删除失败，请重试');
    console.error('删除活动错误:', error);
  }
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  return date.toLocaleString();
};

// 获取状态名称
const getStatusName = (status) => {
  const statuses = {
    1: '未发布',
    2: '已发布',
    3: '进行中',
    4: '已结束'
  };
  return statuses[status] || '未知';
};

// 获取状态标签类型
const getStatusType = (status) => {
  const types = {
    1: 'info',
    2: 'success',
    3: 'warning',
    4: 'primary'
  };
  return types[status] || 'info';
};
</script>

<style scoped lang="scss">
.activity-management-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-top: 10px;
}

.table-card {
  min-height: 500px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.warning-text {
  color: #ff4d4f;
  margin-top: 10px;
}

.user-name {
  font-weight: bold;
  color: #2563eb;
}

/* 对话框样式调整 */
.el-dialog__body {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 18px;
}

/* 禁用按钮样式 */
.el-button:disabled {
  cursor: not-allowed;
  opacity: 0.6;
}
</style>    